/**
 * init
 */
/**
 * 随机高度，随机图片，布局函数
 */
var wf = {
  // 返回随机高宽的图片
  rdmImg: function () {
    var width = Math.floor(Math.random() * 100) + 300,
      height = Math.floor(Math.random() * 500) + 300;
    return "http://placekitten.com/" + height + '/' + width;
  },
  // 进行排列
  arrange: function (index) {
    var colsHeight = [0, 0];
    var lastColsHeight = 0;
    let itemWidth = 186;
    // 计算出列
    let cols = 2;
    $(".photo-container").each(function (e) {
      let col = 0, style = "";
      // 获取第一个容器的宽
      if (colsHeight[0] <= colsHeight[1]) {
        col = 0;
        style = 'left:' + (col * itemWidth) + 'px;';
      } else {
        col = 1;
        style = 'left:' + (col * itemWidth + 3) + 'px;';
      }
      style += "top :" + colsHeight[col] + "px;"
      $(this).attr("style", style);
      colsHeight[col] += $(this).height();
      var more = document.getElementById("mainScrolldroploadDOM");
      if(colsHeight[col]>lastColsHeight){
        more.style.top = ( colsHeight[col] +10 )+ "px";
        lastColsHeight = colsHeight[col];
      }

      // if(index == 9) {
      //    more.style.display = 'block';
      // }else {
      //    more.style.display = 'none';
      // }
    });
  },
}



export default {
  data() {
    return {
      // tab组
      tabs: {
        "prise": true,
        "warn": false,
        "problem": false
      },
      // 可点击
      canClick: true,
      tabkey: '',
      // 加载更多
      load: false,
      // 是否有新评论
      hasComment: false,
      // 图片组
      photos: false,
      // 图片张数
      photosNum: '',
      // 当前页
      pageNum: 1,
      // 当前页
      curPage: 0,
      // 每页条数
      pageSize: 10,
      // 显示数据
      showData: false,
      //轮播图列表
      slideshowList:[],
      //是否显示操作按钮
      showActionFlag:false,
      mySwiper:'',
      timestamp:0,
    }
  },
  filters: {
    thumbnail: function (url, param) {
      return url.replace(".png", param + ".png").replace(".jpg", param + ".jpg")
    },
    /**
     * @description 返回18个字符  如果超过18个 追加...
     */
    subStrings: function (str,subjectName) {
      str = str.replace(/[\r\n]{1,}/g,"　").replace(/[\r\n]$/g,'');
      let len;
      if(subjectName){
        len = subjectName.length;
      }else{
        len = 0;
      }
      return (len+str.length) > 18 ? str.substr(0, 18-len) + '...' : str
    },
    /**
     * 0 => 赞
     */
    changeVote: function (num) {
      return num > 0 ? num  > 9999 ? (num/10000).toFixed(1).replace('.0', '') + 'W' : num : '赞'
    },
    /**
     * 0 => 评论
     */
    changeDis: function (num) {
      return num > 0 ? num  > 9999 ? (num/10000).toFixed(1).replace('.0', '') + 'W' : num : '评论'
    },
  },
  beforeRouteEnter(to, from, next) {
    if(from.name !='detailPraising' && from.name !='detailReport' && from.name !='subjectList'){
      sessionStorage.removeItem('scrollTop');
      sessionStorage.removeItem('counts');
    }
    next();
  },
  mounted() {
    this.init();
    document.getElementById('mainScroll').addEventListener('scroll',this.hideAction);
  },
  activated(){
    //初始化
    this.$util.setTitle('随手拍');
    this.showActionFlag = false;
    if(this.mySwiper){
      //销毁旧的swiper实例，创建新swiper
      this.mySwiper.destroy();
      this.mySwiper = new Swiper ('.swiper-container', {
        direction: 'horizontal',
        loop: true,
        autoplay : 3000,
        autoplayDisableOnInteraction : false,

        // 如果需要分页器
        pagination: '.swiper-pagination',
        bulletActiveClass: 'paginationcurrent',
        onClick: function(swiper,e){
          $(".swiper-slide-duplicate-active").click();
        }

      });

    }
    //高度定位
    if( this.$util.sessionData('scrollTop')){
      document.getElementById('mainScroll').scrollTop = this.$util.sessionData('scrollTop');

    }else if( this.$util.sessionData('scrollTop') == '0'){
      document.getElementById('mainScroll').scrollTop = 0;
    }
    //同步列表点赞、评论数据
    if(this.$util.sessionData('counts')){
      let counts = JSON.parse(this.$util.sessionData('counts'));
      this.photos[counts.index].praiseCount = counts.praiseCount;
      this.photos[counts.index].commentCount = counts.commentCount;
      this.photos[counts.index].praised = counts.praised;
    }
    //获取评论状态
    this.getCommentStatus();
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    // this.$util.droploadUpOnScroll()
    if(to.name == 'detailPraising'||to.name == 'detailReport'||to.name == 'subjectList'){
      let scrollTop = document.getElementById('mainScroll').scrollTop;
      if(scrollTop){
        this.$util.sessionData('scrollTop',scrollTop);
      }else if(scrollTop == 0){
        this.$util.sessionData('scrollTop','0');
      }

    }else{
      this.$util.sessionData('scrollTop','0');
    }
    next();
  },
  methods: {
    init() {
      this.$util.setTitle('随手拍');

      //获取轮播图列表
      this.getSlideshowList();
      //获取随手拍列表
      let tabKey = this.$util.sessionData('tabkey');
      if(tabKey) {
        console.warn(tabKey)
        if(tabKey == 'prise') {
          this.changeTabs('prise')
        }else if(tabKey == 'warn') {
          this.changeTabs('warn')
        }else if(tabKey == 'problem') {
          this.changeTabs('problem')
        }
      }else {
        this.$util.droploadUpOnScroll( {ele: 'mainScroll'}, this.queryPhotoList )
        this.queryPhotoList();
      }
      //this.getCommentStatus();
    },

    /**
     * 获取轮播图列表
     * /convSubject/getSlideshowList
     */
    getSlideshowList() {
      let _this = this;
      _this.$http.post('/convSubject/getSlideshowList', {}, {loading: true}).then(function (rep) {
        console.log(rep)
        if (rep.meta && rep.meta.code == '0') {
          _this.slideshowList = rep.data;
          //创建轮播图实例
          setTimeout(function(){
            _this.mySwiper = new Swiper ('.swiper-container', {
              direction: 'horizontal',
              loop: true,
              autoplay : 3000,
              autoplayDisableOnInteraction : false,

              // 如果需要分页器
              pagination: '.swiper-pagination',
              bulletActiveClass: 'paginationcurrent',
              onClick: function(swiper,e){
                $(".swiper-slide-duplicate-active").click();
              }

              // 如果需要前进后退按钮
              // nextButton: '.swiper-button-next',
              // prevButton: '.swiper-button-prev',

            });
          },200)
        }
      }).catch(function (err) {
        console.log(err)
      })
    },


    /**
     * 获取有新评论的状态
     * /convphoto/getCommentStatus
     */
    getCommentStatus() {
      let _this = this;
      _this.$http.post('/convphoto/getCommentStatus', {}, {loading: false}).then(function (rep) {
        console.log(rep)
        if (rep.meta && rep.meta.code == '0') {
          _this.hasComment = rep.data;
        }
      }).catch(function (err) {
        console.log(err)
      })
    },

    /**
     * 获取赞美北京列表
     */
    queryPhotoList() {
      let _this = this;

      //如果当前页==下一页则不发请求
      if (this.pageNum == this.curPage) {
        return
      } else {
        this.curPage = this.pageNum;
      }
      // 如果数组
      if(this.photos && this.photos.length >= 10) {
        _this.load = true;
      }
      var params = {
        "pageNum": _this.pageNum,
        "pageSize": _this.pageSize
      };
      this.$http.post("praisingCity/getPhotoList", params,{loading:false}).then(function (rep) {
        _this.load = false;
        if (rep.meta && rep.meta.code == '0') {
          // 获取数据完成
          _this.canClick = true;
          let datas = rep.data || [];
          if (!_this.photos) {
            _this.photos = []
          }
          //
          if (datas.length > 0) {
            _this.timestamp = new Date().getTime();
            _this.loadImg(datas, 0,_this.timestamp);
          } else {
            _this.showData = true;
          }
          // 隐藏加载更多
          if(datas.length < _this.pageSize) {
            _this.$util.droploadUpOnScroll( {ele: 'mainScroll', text: ' ', stop: true})
          }

        }
      }).catch(function (err) {
        console.log(err);
      })
    },

    /**
     * 获取社会警示
     */
    querySocialWarningList() {
      //如果当前页==下一页则不发请求
      if (this.pageNum == this.curPage) {
        return
      } else {
        this.curPage = this.pageNum;
      }
      let _this = this;
      var params = {
        "pageNum": _this.pageNum,
        "pageSize": _this.pageSize
      };
      this.$http.post("/convphoto/getSocialWarningList", params,{loading:false}).then(function (rep) {
        if (rep.meta && rep.meta.code == '0') {
          // 获取数据完成
          _this.canClick = true;
          let datas = rep.data || [];
          if (!_this.photos) {
            _this.photos = []
          }
          if (datas.length > 0) {
            _this.timestamp = new Date().getTime();
            _this.loadImg(datas, 0,_this.timestamp);
          } else {
            _this.showData = true
          }

          // 隐藏加载更多
          if(datas.length < _this.pageSize) {
            _this.$util.droploadUpOnScroll( {ele: 'mainScroll', text: ' ', stop: true})
          }
        }
      }).catch(function (err) {
        console.log(err);
      })
    },


    /**
     * 获取问题处理列表
     */
    queryProblemHandList() {
      //如果当前页==下一页则不发请求
      if (this.pageNum == this.curPage) {
        return
      } else {
        this.curPage = this.pageNum;
      }
      let _this = this;
      var params = {
        "pageNum": _this.pageNum,
        "pageSize": _this.pageSize
      };
      this.$http.post("/convphoto/getProblemHandList", params,{loading:false}).then(function (rep) {
        _this.loadHide = false;
        if (rep.meta && rep.meta.code == '0') {
          // 获取数据完成
          _this.canClick = true;
          let datas = rep.data || [];
          if (!_this.photos) {
            _this.photos = []
          }
          if (datas.length > 0) {
            _this.timestamp = new Date().getTime();
            _this.loadImg(datas, 0, _this.timestamp);
          } else {
            _this.showData = true
          }
          // 隐藏加载更多
          if(datas.length < _this.pageSize) {
            _this.$util.droploadUpOnScroll( {ele: 'mainScroll', text: ' ', stop: true})
          }
        }
      }).catch(function (err) {
        console.log(err);
      })
    },






    /**
     * 切换页签
     */
    changeTabs(key) {
      let item;
      let _this = this;
      if(_this.canClick) {
        _this.canClick = false;
      }else {
        return;
      }
      // 所有数据初始化
      // 图片组
      _this.photos = false,
        // 当前页
        _this.pageNum = 1,
        // 当前页
        _this.curPage = 0,
        // 每页条数
        _this.pageSize = 10,
        // 显示数据
        _this.showData = false


      // 选中
      for (item in _this.tabs) {
        if (item == key) {
          _this.tabs[item] = true
        } else {
          _this.tabs[item] = false
        }
      }


      // 切换执行对应的方法
      if (key == 'prise') {
        // console.log('prise');
        _this.queryPhotoList();
        _this.$util.droploadUpOnScroll( {ele: 'mainScroll'},_this.queryPhotoList );
        _this.$util.sessionData('tabkey', 'prise');
      }

      if (key == 'warn') {
        // console.log('warn')
        _this.querySocialWarningList();
        _this.$util.droploadUpOnScroll( {ele: 'mainScroll'}, _this.querySocialWarningList );
        _this.$util.sessionData('tabkey', 'warn');
      }

      if (key == 'problem') {
        // console.log('problem')
        _this.queryProblemHandList();
        _this.$util.droploadUpOnScroll( {ele: 'mainScroll'}, _this.queryProblemHandList );
        _this.$util.sessionData('tabkey', 'problem');
      }

    },
    /**
     * 排列组合
     */
    arrange(index) {
      let _this = this;
      if (_this.photos[index] && _this.photos[index].photo) {
        _this.photos[index].photo = _this.photos[index].photo.replace("_17_2048_1_0.png", "_290_2048_100_0.png").replace("_17_2048_1_0.jpg", "_290_2048_100_0.jpg");
        _this.photos[index].load = true;
      }
      wf.arrange(index);
    },
    /**
     * 加载图片
     * @param {*} arr
     * @param {*} index
     */
    loadImg(arr, index,timestamp) {
      let _this = this;
      let img = new Image();
      img.onerror = function () {
        nextImg();
        arr[index].load = true;
      };
      img.onload = nextImg;
      function nextImg() {
        if(Array.isArray(_this.photos) && _this.timestamp ==timestamp){
          _this.photos.push(arr[index]);
        }
        if (index < arr.length) {
          _this.loadImg(arr, index + 1,timestamp);
          //是否有下一页
          if (index + 1 >= _this.pageSize) {
            _this.pageNum++;
          }
        }
      }
      if (arr[index] && arr[index].photo) {
        //缩略图高度传最大值2048，按宽度（较小值）等比缩放
        img.src = arr[index].photo.replace(".png", "_17_2048_1_0.png").replace(".jpg", "_17_2048_1_0.jpg");
        arr[index].photo = arr[index].photo.replace(".png", "_17_2048_1_0.png").replace(".jpg", "_17_2048_1_0.jpg")
        arr[index].load = false;
      }
    },

    /**
     * 点赞
     */
    praise(item) {
      let _this = this;
      let param = {
        "id": item.id
      }
      _this.$http.post('/praisingCity/praise', param, {loading: false}).then(function (rep) {
        if (rep.meta && rep.meta.code == '0') {
          item.praised = !item.praised;
          if (item.praised) {
            item.praiseCount = item.praiseCount - 0 + 1;
          } else {
            item.praiseCount = item.praiseCount - 0 - 1;
          }
        }
      }).catch(function () {

      })
    },
    /**
     * 跳转详情
     */
    godetail(id,index, key) {
      // 问题处理
      if (key == "problem") {
        // 问题处理
        this.$router.push({ 'name': 'detailReport', params: { 'id': id},query:{'index':index } });
      } else {
        // 大赞北京  社会警示
        this.$router.push({ 'name': 'detailPraising', params: { 'id': id },query:{'index':index } });
      }

    },

    /**
     * 发起随手拍
     */
    goPhoto() {
      this.$router.push({ 'name': 'issue'})
    },
    /**
     * 跳转我的随手拍
     */
    goMyPhoto() {
      this.$router.push({ 'name': 'list' })
    },

    /**
     * 跳转专题详情页
     */
    goSubject(subjectId){
      this.$router.push({'name':'subjectList',params: { 'subjectId': subjectId }})
    },
    /**
     * 显示操作按钮
     */
    showAction(){
      if(this.showActionFlag == "active"){
        this.showActionFlag = "unactive"
      }else{
        this.showActionFlag = "active"
      }
    },
    /**
     * 跳转随手拍介绍页
     */
    goIntroduce(){
      this.$router.push({'name':'introduction'})
    },
    hideAction(){
      if(this.showActionFlag == "active"){
        this.showActionFlag = "unactive"
      }
    }
  }
}
